import Component, { get, post, forceLogin, middleware } from '../ZES';
import jwt from 'jsonwebtoken';
import crypto from 'crypto';
export const JWT_SECRET = 'XXRC+U53R*541T**';
const passwordSalt = 'PWST--ppwwsstt';

export default class User extends Component {

    @post @get
    async register(cx) {
        let { username, password } = cx.params();
        cx.assert.notEmpty(username, password);
        password = crypto.createHash('md5').update(password + passwordSalt).digest('hex');
        let result = await cx.db.insert('account', { username, password });
        if (result.insertId) {
            let userInfo = { 'uid': result.insertId, username };
            await new cx.model.User(userInfo).save();
            let token = jwt.sign(userInfo, JWT_SECRET);
            //console.log('token', token);
            cx.cookies.set('rc-auth', token, { path: '/' });
            return { userInfo };
        } else {
            cx.fail('注册失败');
        }
    }

    @post @get
    async login(cx) {
        let { username, password } = cx.params();
        cx.assert.notEmpty(username, password);
        password = crypto.createHash('md5').update(password + passwordSalt).digest('hex');
        let result = await cx.db.queryOne('account', { username, password });
        if (result) {
            let userInfo = await cx.model.User.findOne({ uid: result.id }, 'nick username uid email phone');
            //console.log(userInfo);
            let token = jwt.sign(JSON.parse(JSON.stringify(userInfo)), JWT_SECRET);
            cx.cookies.set('rc-auth', token, { path: '/' });
            return userInfo;
        } else {
            cx.fail('账号或密码错误');
        }
    }


    @get @post @middleware(forceLogin)
    async changeUserInfo(cx) {
        let newInfo = {
            nick: cx.param('nick')
        };
        await cx.model.User.findByIdAndUpdate(cx.state.user._id, newInfo);
    }

    @get
    logout(cx) {
        cx.cookies.set('rc-auth', '');
    }


    @get @middleware(forceLogin)
    info(cx) {
        return cx.state.user;
    }
}